//app.js
import {
  httpRequest,
  httpSetApp

} from './utils/http.js'

const UNPROMPTED = 0 // 未请求
const AUTHORIZED = 1 // 同意
const UNAUTHORIZED = 2 // 拒绝

App({
  onLaunch: function(options) {
    const that = this
    httpSetApp(this.globalData)
    console.log(options, '小程序启动参数')
    // if(options.scene==1011){
    //     wx.switchTab({
    //       url: '/pages/play/index',
    //     })
    // }
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function() {
      updateManager.applyUpdate()
    })
    updateManager.onUpdateFailed(function() {
      updateManager.applyUpdate()
    })
  },
  globalData: {
    userInfo: null,
    basicUrl: 'https://apikb.zjkbtc.com/prod-api/', //坤泊
    // basicUrl: 'https://www.zjkbtc.com/prod-api/', //廊慧
    //  http://hellopop.51vip.biz/,   basicUrl:'http://stcar.easy.echosite.cn/'
    openId: "",
    userId: 0,
    code: ""
  },
  httpRequest: httpRequest,
  // 查看是否授权
  getSetting(sucFn, direct) {
    var that = this;
    wx.getSetting({
      withSubscriptions: true,
      success(e) {
        if (e.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              that.globalData.userInfo = res.userInfo
              wx.setStorageSync('userInfo', res.userInfo)
              if (wx.getStorageSync("userId") && wx.getStorageSync("userId")) {
                that.globalData.openId = wx.getStorageSync("openId")
                that.globalData.userId = wx.getStorageSync("userId")
                sucFn()
              } else {
                console.log(direct, '跳转参数')
                if (direct == 'pay') {
                  wx.navigateTo({
                    url: '/pages/user/index?url=pay',
                  })
                } else {
                  wx.navigateTo({
                    url: '/pages/user/index',
                  })
                }
              }
            }
          })
        } else {
          console.log(e, '未授权')
          wx.navigateTo({
            url: '/pages/user/index',
          })
        }
      },
      fail(e) {
        console.log(e, '获取设置失败')
      }
    })
  },

  // 登录
  doLogin: function(aaa, cb) {
    this.globalData.userInfo = aaa.userInfo
    wx.setStorageSync('userInfo', aaa.userInfo)
    return new Promise((resolve, reject) => {
      let that = this;
      wx.login({
        success: function(loginRes) {
          if (loginRes.code) {
            //wx.login获取code。
            console.log('获取成功的code', loginRes.code);
            that.globalData.code = loginRes.code;
            //发起网络请求
            console.log(aaa, '用户信息')
            cb()
          } else {
            // 获取 code 失败
            resolve()
            console.log('调用wx.login获取code失败');
          }
        },
        fail: function(error) {
          resolve()
          // 调用 wx.login 接口失败
        }
      });

    })
  },
  wxLogin(res, direct) {
    let that = this;
    // let codeStr = wx.getStorageSync('code')
    let userInfo = wx.getStorageSync('userInfo')
    let avatar = userInfo.avatarUrl
    let nickNameStr = userInfo.nickName
    let sessionKey = wx.getStorageSync('sessionKey');
    let encryptedData = res.detail.encryptedData
    let iv = res.detail.iv;
    let sex = userInfo.gender
    // httpRequest('user/WxLogin/login', 'POST', {
    httpRequest('user/WxLogin/login', 'POST', {
        code: that.globalData.code,
        avatarurl: avatar,
        encryptedData: encryptedData,
        iv: iv,
        userName: nickNameStr,
        sex: sex,
      })
      .then(res => {
        //存储用户信息到全局
        if (res.statusCode == 200) {
          console.log('login', res);
          wx.setStorageSync('userId', res.data.data.userId)
          wx.setStorageSync('openId', res.data.data.openId)
          wx.setStorageSync('phone', res.data.data.phone)
          that.getVeriCode(res, direct)
        } else {
          wx.showToast({
            icon: 'none',
            title: '登录失败',
          })
        }
      })
  },
  getVeriCode(userData, direct) {
    let that = this,
      userInfo = wx.getStorageSync('userInfo')
    httpRequest('code', 'GET', {})
      // user/
      .then(res => {
        console.log(res, '密码等信息')
        httpRequest('auth/oauth/token', 'GET', {
            username: wx.getStorageSync('userId'),
            password: '123456',
            code: res.data.verifyCode,
            uuid: res.data.uuid,
            client_id: 'web',
            client_secret: '123456',
            grant_type: 'password',
            scope: 'server'
          })
          .then(e => {
            console.log(e, '获取令牌')
            that.globalData.access_token = e.data.data.access_token
            wx.setStorageSync('access_token', e.data.data.access_token)
            wx.showToast({
              title: '登录成功'
            })
            setTimeout(function() {
              if (userData.data.data && userData.data.data.userPlateList && userData.data.data.userPlateList.length > 0) {
                wx.navigateBack()
              } else {
                if (direct == 'pay') {
                  wx.redirectTo({
                    url: '/pages/carInformation/index?url=pay',
                  })
                } else {
                  wx.redirectTo({
                    url: '/pages/carInformation/index',
                  })
                }
              }
            }, 1000)
          })
          .catch(e => {
            wx.showToast({
              icon: 'none',
              title: '登录失败',
            })
          })
      })
      .catch(e => {
        wx.showToast({
          icon: 'none',
          title: '登录失败',
        })
      })
  },
  checklogin: function() {
    const that = this
    return new Promise((resolve, reject) => {
      if (wx.getStorageSync('sessionKey')) {
        if (that.userInfo.roles == null) {
          that.doLogin()
        } else {
          resolve()
        }
      } else {
        reject("未登录")
      }
    })
  },
  onPayCancel(target, url, params){
    let that=this;
    target.hideModal();
    wx.request({
      url: that.globalData.basicUrl + url,///?orderId='+target.options.item+'&orderNum='+target.data.orderNum
      method: "POST",
      data: params,
      success: function (res) {
        var orderId = this;
        console.log(res);
        if (res.data.code == 200) {
          wx.showToast({
            title: '支付成功',
            icon: "none",
            duration: 2000,
            success: function () {
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }, 2000)

            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 3000,
            success: function () {
              // setTimeout(() => {
              //   wx.switchTab({
              //     url: '/pages/play/index',
              //   })
              // }, 2000)
            }
          })
        }
      },
      fail: function (err) {
        console.log('err', err);
      }
    })
  },
  onPayConfirm(target, url, params,method) {
    let that = this
    target.hideModal();
    let openId = wx.getStorageSync('openId')
    wx.request({
      url: that.globalData.basicUrl + url+ '/?openId=' + openId + params,
      method:method || 'GET',
      success: function(res) {
        var orderId = this;
        console.log(res);
        if (res.statusCode == 200) {
          if (res.data.total_fee == 0) {
            wx.showModal({
              content: '该订单在免费时段中，是否结束？',
              success(e) {
                if (e.confirm) {
                  that.orderFree(res)
                }
              }
            })
          } else {
            wx.requestPayment({
              timeStamp: res.data.timeStamp,
              package: res.data.package,
              paySign: res.data.paySign,
              appId: res.data.appId,
              signType: res.data.signType,
              nonceStr: res.data.nonceStr,
              success: function(res) {
                wx.showToast({
                  title: '支付成功',
                  duration: 2000,
                  success: function() {
                    setTimeout(() => {
                      wx.switchTab({
                        url: '/pages/index/index',
                      })
                    }, 2000)
                  }
                })
              }
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          })
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '支付失败',
          duration: 2000,
          success: function() {
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/play/index',
              })
            }, 2000)
          }
        })
      }
    })
  },
  orderFree(res) {
    let that = this;
    wx.request({
      url: that.globalData.basicUrl + 'user/wxPay/localSuccess',
      data: res.data,
      method: 'POST',
      success(e) {
        console.log(e, '免费订单结束')
        wx.showToast({
          title: '订单已结束',
          duration: 1500,
          success() {
            wx.navigateBack()
          }
        })
      }
    })
  },
})